/**
 * 兼容h5 weapp环境
 * developed by wenjiahui
 */

import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState, useEffect } from "react";
import LgSearch from "./search";
import TeachingGroup from "./images/选择-教研组.png";
import Grade from "./images/选择-年级.png";
import AllUser from "./images/选择-全校人员.png";
import Department from "./images/选择-行政组织.png";
import LgButton from "../button";
import ArrowTop from "./images/向上.png";
import {
  arraySome,
  arraySomeDouble,
  concatArray,
  debounce,
  DeepClone,
  delItemFromArray,
  editArrayItem,
  executeId,
  getCheckValue,
  getIsMapArray,
  removeArrayChild,
  throttle,
} from "./myUtils";
import Row from "./Row";
import LgEmptyContent from "../emptyContent";
import Crumbs from "./crumbs";
import RightArrow from "./images/路径.png";
import DepartmentAvatar from "./images/头像-部门.png";
import StudentAvatar from "./images/头像-学生.png";
import ParentAvatar from "./images/头像-家长.png";
import TeacherAvatar from "./images/头像-教师.png";
import AdminAvatar from "./images/头像-管理员.png";
import OtherAvatar from "./images/头像-其他教职工.png";
import ClassAvatar from "./images/头像-班级.png";
import GradeAvatar from "./images/头像-年级.png";
import TeachingAvatar from "./images/头像-教研组.png";
import ChatAvatar from "./images/头像-讨论组.png";
import PrepareAvatar from "./images/头像-备课组.png";
import LgCheckbox from "../checkbox";
import { LgPopLayer } from "../popLayer";
import { SelectUserProps } from "./type";
import "./index.scss";

let currentType = "";

function App(props: SelectUserProps) {
  const {
    token,
    officeUrl,
    groupUserType,
    recentList = [],
    selectUserList = [],
    backData = "user",
    isEmptyForbid = true,
    allSelectObj,
    onConfirm,
  } = props;

  const getGroupAvatar = (item: any) => {
    //获取groupIcon
    if (item.avatar) {
      return item.avatar;
    }
    let avatar = DepartmentAvatar;
    let logotype = item.logotype || item.groupName;
    if (!logotype) {
      return avatar;
    }
    if (logotype.includes("班级")) {
      avatar = ClassAvatar;
    } else if (logotype.includes("学院")) {
      avatar = GradeAvatar;
    } else if (logotype.includes("年级")) {
      avatar = GradeAvatar;
    } else if (
      (logotype.includes("教研组") || logotype.includes("教学组")) &&
      logotype !== "全部教研组"
    ) {
      avatar = TeachingAvatar;
    } else if (logotype.includes("管理员") || item?.groupId?.includes("IC")) {
      avatar = AdminAvatar;
    } else if (logotype.includes("学生")) {
      avatar = StudentAvatar;
    } else if (logotype.includes("备课组")) {
      avatar = PrepareAvatar;
    } else if (logotype.includes("老师")) {
      avatar = TeacherAvatar;
    } else if (logotype.includes("家长")) {
      avatar = ParentAvatar;
    } else if (logotype.includes("其他人员")) {
      avatar = OtherAvatar;
    } else if (logotype.includes("讨论组")) {
      avatar = ChatAvatar;
    } else {
      avatar = GradeAvatar;
    }
    return avatar;
  };

  const subListAttr = [
    "structureVoList",
    "structureVoList",
    "structureVoList",
    "structureVoList",
    "structureVoList",
    "structureVoList",
  ];

  const [routerList, setRouterList] = useState([]);

  const [selectList, setSelectList] = useState([]);
  const [crumbs, setCrumbs] = useState<any>([{ lable: "全部" }]); //面包屑
  const [dataList, setDataList] = useState<any>([]);
  const [myGroupList, setMyGroupList] = useState([]);
  const [searchResultList, setSearchResultList] = useState<any>([]);
  const [showSearchArea, setShowSearchArea] = useState(false);
  const [keyword, setKeyword] = useState("");
  const [showSelected, setShowSelected] = useState(false);
  const [historySelected, setHistorySelected] = useState([]);
  const [showRouter, setShowRouter] = useState(false);
  const [userInfo, setUserInfo] = useState<any>({});

  const searchUserHandle = debounce(
    (value) => {
      if (!value) {
        setKeyword("");
        return;
      }
      setShowSearchArea(true);
      setKeyword(value);
      Taro.showLoading();

      let url = officeUrl + "/api/common/user/searchUser";
      let body: any = {
        schoolId: userInfo.schoolId,
        userName: value.trim(),
        size: 200,
        page: 1,
      };

      if (userInfo.userType == 2 || userInfo.userType == 3) {
        url = officeUrl + "api/contact/selectObject/search/myClass";
        body = {
          userId: userInfo.userId,
          userType: userInfo.userType,
          schoolId: userInfo.schoolId,
          schoolLevel: userInfo.schoolLevel,
          keyword: value.trim(),
          groupId: userInfo.groupId,
        };
      }
      Taro.request({
        url,
        data: body,
        header: {
          Authorization: token,
        },
      })
        .then((res: any) => {
          if (res.code == 200) {
            let result = res.data;
            let searchList = result?.slice(0, 200);
            Taro.hideLoading();
            getIsMapArray(searchList) &&
              searchList.forEach((item: any) => {
                item.id = item.userId + item.userName;
                if (arraySome(selectList, item, "userId")) {
                  item.hasCho = 1;
                } else {
                  item.hasCho = 0;
                }
              });
            if (getIsMapArray(groupUserType)) {
              searchList = searchList.filter((i) =>
                groupUserType?.includes(i.userType)
              );
            }
            setSearchResultList(searchList);
          } else {
            Taro.showToast({
              title: res.msg || "请求出错",
              icon: "none",
            });
          }
        })
        .catch(() => {
          Taro.showToast({
            title: "请求出错",
            icon: "none",
          });
        });
    },
    300,
    { trailing: true }
  );

  //计算选取到的用户显示名称
  const getNameStr = (arr) => {
    let nameArr =
      getIsMapArray(arr) &&
      arr.map(
        (item) => item.userName || `${item.groupName}(${item.totalCount || 0})`
      );
    return nameArr.join("、");
  };

  // 获取显示的选取数量 策略：不计入重复的用户，只根据userId判断
  const getSelectNumber = (arr) => {
    let num = 0;
    let alreadySelect = getDeepUser(arr);
    num = alreadySelect?.length || 0;

    return num;
  };

  //点击面包屑
  const handleHistory = (item, e) => {
    // console.log(item)
    if (item.lable === "全部") {
      setShowRouter(false);
      setCrumbs([{ lable: "全部" }]);
      return;
    }

    var index = e.currentTarget.dataset.index;
    var newList = new Array();
    crumbs.forEach((o, i) => {
      if (i <= index) {
        newList.push(o);
      }
    });
    setCrumbs(newList);
  };

  //向面包屑中添加地址
  const handleCrumb = (item) => {
    if (arraySome(crumbs, item, "lable")) {
      return;
    }

    let arr = DeepClone(crumbs);
    item["level"] = arr[arr.length - 1]?.level
      ? arr[arr.length - 1]?.level + 1
      : 2;
    item["lable"] = item.lable || item.groupName;
    arr.push(item);
    setCrumbs(arr);

    let curData = getCurListData(
      currentType === "router" ? DeepClone(routerList) : DeepClone(myGroupList),
      arr
    );
    setDataList(curData);
  };

  //处理数据
  function treeMap(data, selectData, groupSign = "0") {
    /**
     * groupSign
     * 0 不区分
     * 2 学生
     * 3 家长
     */
    const hasChild = getIsMapArray(data.selectObjectUserVoList);
    const hasChild2 = getIsMapArray(data.structureVoList);
    const hasChild3 = hasChild && hasChild2;
    // 可以根据实际开发需要返回自己想要的key值
    if (hasChild3) {
      data.selectObjectUserVoList = concatArray(
        data.structureVoList,
        data.selectObjectUserVoList,
        null
      );
    }

    if (data.userId) {
      data.avatarPath = data.avatarPath || data.photoPath;
      data.photoPath = data.photoPath || data.avatarPath;
      return {
        name: data.userName,
        id: data.userId + data.userName,
        isLast: true,
        info: data,
        ...data,
        hasCho: arraySome(selectData, data, "userId") ? 1 : 0,
        // structureVoList: hasChild ? data.selectObjectUserVoList.map(i => treeMap(i)) : hasChild2 ? data.structureVoList.map(i => treeMap(i)) : []
      };
    } else {
      const { logotype, groupName } = data || {};
      let currentGroupSign = groupSign;
      if (logotype === "学生" && groupName === "学生") {
        currentGroupSign = "2";
      } else if (logotype === "家长" && groupName === "家长") {
        currentGroupSign = "3";
      }

      data.groupSign = currentGroupSign;
      if (arraySome(selectData, data, "groupId")) {
        //传入的group需要给它赋值子项
        setSelectList((list) => {
          let dealSelect = DeepClone(list);
          dealSelect.forEach((item) => {
            if (item.groupId == data.groupId && !item.structureVoList) {
              if (!item.avatar) {
                item.avatar = "";
              }
              item.id = executeId(item);
              item.name = item.groupName;
              item.structureVoList =
                data.structureVoList || data.selectObjectUserVoList;
              item.avatar = getGroupAvatar(item);
              item.totalCount = data.totalCount;
            }
          });
          return dealSelect;
        });
      }

      return {
        name: data.groupName,
        id: data.groupId + data.groupName + data.groupSign,
        hasCho: arraySomeDouble(selectData, data, "groupId", "groupSign")
          ? 1
          : 0,
        groupName: data.groupName,
        groupId: data.groupId,
        totalCount: data.totalCount || data?.structureVoList?.length || 0,
        isLast: false,
        groupSign: currentGroupSign,
        avatar: getGroupAvatar(data),
        text: data.text || "",
        logotype: data?.logotype || "",
        structureVoList: hasChild
          ? data.selectObjectUserVoList.map((i) =>
              treeMap(i, selectData, currentGroupSign)
            )
          : hasChild2
          ? data.structureVoList.map((i) =>
              treeMap(i, selectData, currentGroupSign)
            )
          : [],
      };
    }
  }

  const handleList = (tree, selectData = selectUserList) => {
    let info = DeepClone(tree);
    return info.map((item) => treeMap(item, selectData));
  };

  const handleChildren = (data, levelIndex, value, type = "router") => {
    if (!data) return;
    var subAttr = subListAttr[levelIndex],
      total = subListAttr.length;
    data.forEach((_o, i) => {
      data[i].hasCho = value;
      if (levelIndex != total) {
        handleChildren(data[i][subAttr], levelIndex + 1, value, type);
      }
    });
  };

  const testMyself = (data) => {
    var flag = 0,
      flag1 = 0;
    for (var i = 0; i < data.length; i++) {
      if (data[i].disabled) continue;
      if (data[i].hasCho == 1) {
        flag = 1;
        if (flag1) return 2;
      } else if (data[i].hasCho == 2) {
        return 2;
      } else {
        flag1 = 1;
        if (flag) return 2;
      }
    }
    return flag;
  };

  const handFormatData = (data, levelIndex, level, type) => {
    // console.log("handFormatData",data, levelIndex, level, type)
    if (!data || !data.length) return -1;
    var subAttr = subListAttr[levelIndex];
    if (!subAttr) return testMyself(data);
    for (var i = 0; i < data.length; i++) {
      data[i]["index"] = i;
      if (data[i].hasCho == 1) {
        data[i]["type"] = type || data[i]["type"] || "";
        handleChildren(
          data[i][subAttr],
          levelIndex + 1,
          1,
          type || data[i]["type"] || ""
        );
      } else {
        var hasCho = handFormatData(
          data[i][subAttr],
          levelIndex + 1,
          level,
          type || data[i]["type"] || ""
        );
        if (hasCho != -1) data[i].hasCho = hasCho;
        data[i].type = type || data[i]["type"] || "";
      }
    }
    return testMyself(data);
  };

  const formatData = (data, type: any = undefined) => {
    var allData = data;
    handFormatData(allData, 0, subListAttr.length, type);
    return allData;
  };

  const handleFormatData = (allData) => {
    //处理初始请求数据
    let handleData = handleList(allData);

    let myGroupData: any = [];
    let routerData: any = [];

    getIsMapArray(handleData) &&
      handleData.map((item) => {
        if (
          item.groupName?.includes("框架") ||
          item.groupName?.includes("架构") ||
          item.groupName === "全校人员"
        ) {
          routerData.push(item);
        } else {
          myGroupData.push(item);
        }
      });
    getIsMapArray(routerData) &&
      routerData.forEach((item: any) => {
        switch (item.groupName) {
          case "行政组织框架":
            item.avatar = Department;
            item.text = "按行政组织架构";
            break;
          case "学校组织框架":
            item.avatar = Department;
            item.text = "按学校组织架构";
            break;
          case "教学教研框架":
            item.avatar = TeachingGroup;
            item.text = "按教研组架构";
            break;
          case "年级组框架":
            item.avatar = Grade;
            item.text = "按年级组架构";
            break;
          case "全校人员":
            item.avatar = AllUser;
            item.text = "按全校人员";
            break;
          default:
            item.avatar = Department;
            item.text = item.groupName;
            break;
        }
      });
    setRouterList(formatData(routerData, "router"));
    setMyGroupList(formatData(myGroupData, "myGroup"));
  };

  const getModalInfo = ({
    schoolId,
    userId,
    schoolLevel,
    userType,
    groupId,
  }) => {
    if (getIsMapArray(allSelectObj)) {
      //传入了数据将不再请求
      let allData = DeepClone(allSelectObj);
      handleFormatData(allData);
      return;
    }
    Taro.showLoading({
      title: "数据加载中...",
      mask: true,
    });
    Taro.request({
      url: officeUrl + "/api/contact/setting/getModule",
      data: {
        schoolId: schoolId,
        schoolLevel: schoolLevel,
        userType: userType,
      },
      header: {
        Authorization: token,
      },
    })
      .then((res: any) => {
        if (res.code == 200) {
          let myModalInfo = res.data;
          const { selfModuleList = [], structureModuleList = [] } = myModalInfo;
          Taro.request({
            url: officeUrl + "/api/contact/selectObject",
            data: {
              userId: userId,
              userType: userType,
              groupId: groupId,
              schoolId: schoolId,
              schoolLevel: schoolLevel,
            },
            header: {
              Authorization: token,
            },
          })
            .then((result: any) => {
              if (result.code == 200) {
                let allData = result.data;
                let visibleData: any = [];
                getIsMapArray(allData) &&
                  allData.forEach((item: any) => {
                    item.moduleName = item.groupName;
                    item.moduleId = item.groupId;
                    if (
                      arraySome(selfModuleList, item, "moduleId") ||
                      arraySome(structureModuleList, item, "moduleId")
                    ) {
                      visibleData.push(item);
                    }
                  });
                if (getIsMapArray(groupUserType)) {
                  let groupDataList = allData.find(
                    (i) => i.groupName === "全校人员"
                  );
                  let currentData: any = [];
                  getIsMapArray(groupDataList.structureVoList) &&
                    groupDataList.structureVoList.forEach((item: any) => {
                      if (groupUserType?.includes(item.groupId)) {
                        currentData.push(item);
                      }
                    });
                  let formatInfo = handleList(currentData);
                  setMyGroupList(formatData(formatInfo, "myGroup"));
                } else {
                  handleFormatData(visibleData);
                }
                Taro.hideLoading();
              } else {
                Taro.showToast({
                  title: result.msg || "请求出错",
                  icon: "none",
                });
              }
            })
            .catch((e) => {
              console.log(e);
              Taro.showToast({
                title: "请求出错",
                icon: "none",
              });
            });
        } else {
          Taro.showToast({
            title: res.msg || "请求出错",
            icon: "none",
          });
        }
      })
      .catch((e) => {
        console.log(e);
        Taro.showToast({
          title: "请求出错",
          icon: "none",
        });
      });
  };

  const getCurListData = (allData, navList = crumbs) => {
    var curData;
    handGetCurListData(allData, 0, navList.length - 1, navList, (data) => {
      curData = data;
    });
    return curData || [];
  };

  const handGetCurListData = (data, levelIndex, level, navList, callBack) => {
    // console.log(data, levelIndex, level)
    if (levelIndex == level) {
      callBack(data);
      return;
    }
    var subAttr = subListAttr[levelIndex];
    if (!subAttr) return;
    for (var i = 0; i < data.length; i++) {
      if (i == navList[levelIndex + 1]["index"]) {
        if (levelIndex == level - 1) {
          callBack(data[i][subAttr]);
        } else {
          handGetCurListData(
            data[i][subAttr],
            levelIndex + 1,
            level,
            navList,
            callBack
          );
        }
      }
    }
  };

  const handleConcatItem = (data, index = 0) => {
    //列表选择
    if (
      data.hasCho === 1 &&
      !arraySome(routerList, data, "id") &&
      !arraySome(myGroupList, data, "id")
    ) {
      // 整组已选不可展开 首页初始不影响
      return;
    }

    let cloneData = DeepClone(data);

    cloneData.index = index;
    let nextData = cloneData.structureVoList;
    getIsMapArray(nextData) &&
      nextData.forEach((item: any) => {
        item.hasCho = getCheckValue(item.structureVoList, "hasCho");
        getIsMapArray(selectList) &&
          selectList.forEach((child: any) => {
            if (child.id === item.id) {
              item.hasCho = 1;
            } else {
              item.hasoCho = 0;
            }
          });
      });
    setShowRouter(true);
    handleCrumb(cloneData);
  };

  const choAll = (data, levelIndex, level, value) => {
    if (!data || !data.length) return -1;
    var subAttr = subListAttr[levelIndex];
    if (levelIndex == level) {
      data.forEach((_o, i) => {
        if (!data[i].disabled) {
          data[i].hasCho = value;
          subAttr && handleChildren(data[i][subAttr], levelIndex + 1, value);
        }
      });
      return value;
    } else {
      if (!subAttr) return -1;
      for (var i = 0; i < data.length; i++) {
        if (i == crumbs[levelIndex + 1]["index"]) {
          var hasCho = choAll(data[i][subAttr], levelIndex + 1, level, value);
          if (hasCho != -1) data[i].hasCho = hasCho;
        }
      }
      return testMyself(data);
    }
  };

  const handelChooseAll = (value) => {
    //全选
    // Taro.showLoading({title:'处理中...',mask:true})
    let selectData = DeepClone(selectList);
    getIsMapArray(selectData) &&
      selectData.forEach((item: any) => {
        //存储当前cumbs 用于删除选中列表定位dataList
        item.crumbs = crumbs;
        if (!item.id) {
          item.id = executeId(item);
        }
      });

    if (!value) {
      selectData = removeArrayChild(selectData, dataList, "id");
    } else {
      selectData = concatArray(selectData, dataList, "id");
    }
    let allData =
      currentType === "router" ? DeepClone(routerList) : DeepClone(myGroupList);
    choAll(allData, 0, crumbs.length - 1, value);
    if (!value) {
      allData = formatData(handleList(allData, selectData));
    }
    currentType === "router" ? setRouterList(allData) : setMyGroupList(allData);
    // Taro.hideLoading()
    // setDataList(getCurListData(allData))
    setSelectList(selectData);
  };

  const chooseSearchItem = (data, value) => {
    //选择搜索项
    // console.log(data, 'searchItem', value)
    let searchData = DeepClone(searchResultList);
    searchData.forEach((item: any) => {
      if (item.userId === data.userId) {
        item.hasCho = value;
      }
    });
    data.id = executeId(data);
    data.name = data.userName || data.groupName;
    setSearchResultList(searchData);
    chooseItem(data, value);
    changeChoStatus(data, value);
  };

  const chooseRecentItem = (data, value) => {
    //最近选择项目
    let recentData = DeepClone(historySelected);
    let selectData = DeepClone(selectList);

    getIsMapArray(selectData) &&
      selectData.forEach((item: any) => {
        //存储当前cumbs 用于删除选中列表定位dataList
        item.crumbs = crumbs;
        if (!item.id) {
          item.id = executeId(item);
        }
      });
    data.id = data.userId + data.userName;
    if (value) {
      selectData = concatArray(selectData, [data], "id");
      recentData = editArrayItem(recentData, data, "hasCho", 1, "id");
    } else {
      selectData = delItemFromArray(data, selectData, "id");
      recentData = editArrayItem(recentData, data, "hasCho", 0, "id");
    }

    changeChoStatus(data, value);
    setHistorySelected(recentData);
    setSelectList(selectData);
  };

  const handleChoItem = (data, levelIndex, level, value, index) => {
    // console.log(data, levelIndex, level, value, index, crumbs)
    if (!data || !data.length) return -1;
    var subAttr = subListAttr[levelIndex];
    for (var i = 0; i < data.length; i++) {
      if (level != levelIndex) {
        if (i == crumbs[levelIndex + 1]["index"] && subAttr) {
          var hasCho = handleChoItem(
            data[i][subAttr],
            levelIndex + 1,
            level,
            value,
            index
          );
          if (hasCho != -1) data[i].hasCho = hasCho;
        }
      } else {
        if (i == index) {
          data[i].hasCho = value;
          subAttr && handleChildren(data[i][subAttr], levelIndex + 1, value);
          break;
        }
      }
    }
    return testMyself(data);
  };

  const chooseItem = (data, value, index = 0) => {
    //选择
    // console.log(data, '###', value, '###', index, '###', selectList)
    if (data.index || data.index === 0) {
      let type = data.type || currentType;
      let allData =
        type === "router" ? DeepClone(routerList) : DeepClone(myGroupList);
      handleChoItem(allData, 0, crumbs.length - 1, value, index);
      type === "router" ? setRouterList(allData) : setMyGroupList(allData);
      // setDataList(getCurListData(allData))
    } else {
      changeChoStatus(data, value);
    }

    let selectData = DeepClone(selectList);
    let recentData = DeepClone(historySelected);
    let cloneData = DeepClone(data);
    cloneData.id = executeId(cloneData);
    cloneData.group = currentType;
    cloneData.index = index;
    cloneData.crumbs = crumbs;
    getIsMapArray(selectData) &&
      selectData.forEach((item: any) => {
        if (!item.id) {
          item.id = executeId(item);
        }
      });
    if (value) {
      selectData = concatArray(selectData, [cloneData], "id");
      recentData = editArrayItem(recentData, cloneData, "hasCho", value, "id");
    } else {
      selectData = delItemFromArray(cloneData, selectData, "id"); //删除单个选中列表
      recentData = editArrayItem(recentData, cloneData, "hasCho", value, "id");
      if (getIsMapArray(cloneData.structureVoList)) {
        selectData = removeArrayChild(
          selectData,
          getDeepChild(cloneData.structureVoList),
          "id"
        );
      }
    }
    setHistorySelected(recentData);
    setSelectList(selectData);
  };

  const handleDelteItem = (
    data,
    levelIndex,
    level,
    value,
    index,
    navList = crumbs,
    type
  ) => {
    if (!data || !data.length) return -1;
    var subAttr = subListAttr[levelIndex];
    for (var i = 0; i < data.length; i++) {
      if (level != levelIndex) {
        if (i == navList[levelIndex + 1]["index"] && subAttr) {
          var hasCho = handleDelteItem(
            data[i][subAttr],
            levelIndex + 1,
            level,
            value,
            index,
            navList,
            type
          );
          if (hasCho != -1) data[i].hasCho = hasCho;
        }
      } else {
        if (i == index) {
          data[i].hasCho = value;
          subAttr &&
            handleChildren(data[i][subAttr], levelIndex + 1, value, type);
          break;
        }
      }
    }
    return testMyself(data);
  };

  const handleChildChange = (data, value) => {
    //修改父节点下所有子节点状态
    getIsMapArray(data) &&
      data.forEach((item: any) => {
        item.hasCho = value;
        if (item.structureVoList) {
          handleChildChange(item.structureVoList, value);
        }
      });
  };

  const hasDeepChild = (structureVoList, data) => {
    return arraySome(getDeepChild(structureVoList), data, "id");
  };

  const handleChange = (allData, data, value) => {
    if (!Array.isArray(allData)) {
      return allData;
    }

    allData.forEach((item) => {
      if (data.id === item.id) {
        item.hasCho = value;
        item.structureVoList && handleChildChange(item.structureVoList, value);
      } else {
        item.hasCho =
          item.hasCho === 1 && hasDeepChild(item.structureVoList, data)
            ? 2
            : item.hasCho;
        item.structureVoList && handleChange(item.structureVoList, data, value);
      }
    });

    return allData;
  };

  const changeChoStatus = (data, value) => {
    let allData = DeepClone(routerList.concat(myGroupList));
    let all = JSON.parse(JSON.stringify(allData));

    handleChange(all, data, value);
    formatData(all);

    let newRouter = all.filter(
      (i) =>
        i.groupName?.includes("框架") ||
        i.groupName?.includes("全校人员") ||
        i.type === "router"
    );
    let newMygroup = all.filter(
      (i) => i.groupName?.includes("我的") || i.type === "myGroup"
    );

    setRouterList(newRouter);
    setMyGroupList(newMygroup);

    return testMyself(data);
  };

  const deleteItem = (data) => {
    let selectData = DeepClone(selectList);
    let recentData = DeepClone(historySelected);
    let cloneData = DeepClone(data);
    cloneData.id = executeId(cloneData);
    //非传入数据的删除
    if (
      (data.index || data.index === 0) &&
      data.crumbs &&
      data.crumbs.length > 1
    ) {
      let type = data.type || currentType;
      let allData =
        type === "router" ? DeepClone(routerList) : DeepClone(myGroupList);
      let currentCrumbs = data?.crumbs || crumbs;
      handleDelteItem(
        allData,
        0,
        currentCrumbs.length - 1,
        0,
        data.index,
        currentCrumbs,
        type
      );
      type === "router" ? setRouterList(allData) : setMyGroupList(allData);
    } else {
      changeChoStatus(cloneData, 0);
    }

    selectData = delItemFromArray(data, selectData, "id"); //删除单个选中列表
    recentData = editArrayItem(recentData, data, "hasCho", 0, "userId");

    setHistorySelected(recentData);
    setSelectList(selectData);
  };

  const getDeepUser = (data, arr: any = []) => {
    //获取树上的所有用户节点 并且去重
    getIsMapArray(data) &&
      data.forEach((item: any) => {
        if (item.userId && !arraySome(arr, item, "userId")) {
          arr.push(item);
        } else if (item.structureVoList) {
          getDeepUser(item.structureVoList, arr);
        } else if (item.selectObjectUserVoList) {
          getDeepUser(item.selectObjectUserVoList, arr);
        }
      });

    return arr;
  };

  const getDeepChild = (data, arr: any = []) => {
    //获取其当前列表下的所有子项名称 包含组与用户
    getIsMapArray(data) &&
      data.forEach((item: any) => {
        arr.push(item);
        if (item.structureVoList) {
          getDeepUser(item.structureVoList, arr);
        }
      });
    return arr;
  };

  const confirm = () => {
    if (!selectList.length && isEmptyForbid) return;
    let arr = backData === "user" ? getDeepUser(selectList) : selectList;
    arr = arr.map((i) => (i?.info ? i.info : i));
    onConfirm(arr);
  };

  const getUserInfo = () => {
    return new Promise((resolve, reject) => {
      Taro.request({
        url: officeUrl + "/api/common/user",
        data: {
          token,
        },
        header: {
          Authorization: token,
        },
      })
        .then((result: any) => {
          if (result.code == 200) {
            resolve(result.data);
          } else {
            reject({ msg: "获取用户信息失败" });
          }
        })
        .catch(() => {
          reject({ msg: "获取用户信息失败" });
        });
    });
  };

  useEffect(() => {
    if (!currentType || (!routerList.length && !myGroupList.length)) {
      return;
    }

    let allData =
      currentType === "router" ? DeepClone(routerList) : DeepClone(myGroupList);

    let curDataList = getCurListData(allData, crumbs);
    // console.log(allData, crumbs, currentType, 'dataList', getCurListData(allData, crumbs))
    setDataList(curDataList);
  }, [crumbs, routerList, myGroupList]);

  useEffect(() => {
    let dealList = DeepClone(selectUserList);
    getIsMapArray(dealList) &&
      dealList.forEach((item: any) => {
        item.id = executeId(item);
        item.name = item.userName || item.groupName;
        item.groupSign = item.groupSign || "0";
      });
    let recentData = DeepClone(recentList);
    getIsMapArray(recentData) &&
      recentData.forEach((item: any) => {
        item.hasCho = 0;
        item.id = item.userId + item.userName;
        item.name = item.userName;
        if (arraySome(selectUserList, item, "userId")) {
          item.hasCho = 1;
        }
      });
    setHistorySelected(recentData);
    setSelectList(() => dealList);
    getUserInfo().then((res: any) => {
      setUserInfo(res);
      getModalInfo(res);
    });
  }, []);

  return (
    <View className="chat_group_select_container">
      <View className="search_area">
        <LgSearch
          placeholder="搜索..."
          onInput={(value) => searchUserHandle(value)}
          onClose={() => {
            setShowSearchArea(false);
          }}
        />
      </View>
      <View className="select_user_body">
        <View className="router_list">
          <View
            className="organization_option"
            style={{ display: routerList?.length ? undefined : "none" }}
          >
            {routerList.map((item: any, index) => {
              return (
                <View
                  className="option_item"
                  key={index}
                  onClick={() => {
                    currentType = "router";
                    handleConcatItem(item, index);
                  }}
                >
                  <Image className="option_item_icon" src={item.avatar} />
                  <View className="option_item_text">{item.text}</View>
                </View>
              );
            })}
          </View>
          <View
            className="my_organization_concat"
            style={{ display: myGroupList.length ? "" : "none" }}
          >
            {getIsMapArray(myGroupList) &&
              myGroupList.map((item: any, index) => {
                return (
                  <View
                    key={index}
                    onClick={() => {
                      currentType = "myGroup";
                      handleConcatItem(item, index);
                    }}
                    className="origanization_item"
                  >
                    <View className="three_icon"></View>
                    <View className="origanization_name">
                      {item?.groupName || item.name}
                    </View>
                    <Image className="more" src={RightArrow} />
                  </View>
                );
              })}
          </View>
          <View className="history_list">
            <View className="history_list_nav">最近选择</View>
            <View className="history_list_box">
              {getIsMapArray(historySelected) ? (
                historySelected.map((item: any, index) => {
                  return (
                    <Row
                      type="D"
                      key={index}
                      data={item}
                      choose={(data, value) => chooseRecentItem(data, value)}
                    />
                  );
                })
              ) : (
                <View style={{ height: "100%" }}>
                  <LgEmptyContent type="B" text="暂无最近选择" />
                </View>
              )}
            </View>
          </View>
          <View
            className="concat_router_list"
            style={{ display: showRouter ? "" : "none" }}
          >
            <Crumbs
              dataList={crumbs}
              onClick={(data, e) => handleHistory(data, e)}
            />
            <View
              className="choose_all_btn"
              style={{ display: dataList.length ? "" : "none" }}
            >
              <LgCheckbox
                type="B"
                value={testMyself(dataList)}
                onClick={(value) => handelChooseAll(value)}
              >
                全选
              </LgCheckbox>
            </View>
            <View className="concat_book">
              {getIsMapArray(dataList) ? (
                dataList.map((item, index) => {
                  return (
                    <Row
                      key={index}
                      index={index}
                      type="D"
                      data={item}
                      onClick={() => handleConcatItem(item, index)}
                      choose={(data, value, i) => chooseItem(data, value, i)}
                    />
                  );
                })
              ) : (
                <LgEmptyContent type="B" />
              )}
            </View>
          </View>
        </View>
        <View
          className="search_result_container"
          style={{ display: showSearchArea ? "" : "none" }}
        >
          <View className="search_result_nav">
            <View className="search_result_nav_text">搜索结果</View>
            <View
              className="search_result_nav_close"
              onClick={() => setShowSearchArea(false)}
            >
              关闭
            </View>
          </View>
          <View className="search_result_list">
            {getIsMapArray(searchResultList) ? (
              searchResultList.map((item, index) => {
                return (
                  <Row
                    type="D"
                    key={index}
                    data={item}
                    keyword={keyword}
                    choose={(data, value) => chooseSearchItem(data, value)}
                  />
                );
              })
            ) : (
              <LgEmptyContent
                type="B"
                className="search_result_empty"
                text={`暂未搜索到关于'${keyword}'的联系人`}
              />
            )}
          </View>
        </View>
        <View className="select_user_footer">
          <View className="member_count">
            已选({getSelectNumber(selectList)}人):
            <View
              className="member_name_list"
              onClick={() => setShowSelected(true)}
            >
              <View className="name_string">
                {getIsMapArray(selectList) ? (
                  <View className="name_str_line">
                    {getNameStr(selectList)}
                  </View>
                ) : (
                  "未选择"
                )}
              </View>
              <Image className="show_select_list" src={ArrowTop} />
            </View>
          </View>
          <LgButton
            type="B"
            width={180}
            height={72}
            style={selectList.length ? undefined : { opacity: "0.5" }}
            className="confirm_select_btn"
            onClick={() => {
              confirm();
            }}
          >
            确定
          </LgButton>
        </View>
      </View>
      <LgPopLayer
        isOpen={showSelected}
        confirm={() => {}}
        showLayer={() => setShowSelected(false)}
        position="bottom"
        title={`已选(${selectList.length || 0})`}
        showClose
      >
        {getIsMapArray(selectList) ? (
          selectList.map((item: any, index) => {
            return (
              <Row
                type="C"
                key={index}
                del={() => deleteItem(item)}
                data={item}
              />
            );
          })
        ) : (
          <View style={{ height: "40vh" }}>
            <LgEmptyContent type="B" text="暂无选择的用户" />
          </View>
        )}
      </LgPopLayer>
    </View>
  );
}
export default App;
